package platformview.richview;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import androidx.annotation.NonNull;

import com.qingning.qn.MainActivity;
import com.qingning.qn.R;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;

import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.platform.PlatformView;
/*
*
* 富文本显示的webview
* */
public class MyPlatformView implements PlatformView {

    private View mNativeView;
    private WebView webView;
    private MethodChannel mChannel;

    Timer mTimer;
    TimerTask mTask;
    int viewHeight=0;
    private MainActivity mContext;



    public MyPlatformView(Context context, MethodChannel channel, Map map, MainActivity activity) {
        mChannel = channel;
        mContext=activity;
        mNativeView = LayoutInflater.from(context).inflate(R.layout.view_my_flutter,null,false);
        webView = mNativeView.findViewById(R.id.webview);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setDisplayZoomControls(false);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); //取消滚动条白边效果
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); //取消滚动条白边效果
        webView.getSettings().setDefaultTextEncodingName("UTF-8") ;
        webView.getSettings().setBlockNetworkImage(false);
        webView.getSettings().setUseWideViewPort(true);//将图片调整到适合webview的大小
        webView.getSettings().setLoadWithOverviewMode(true);// 缩放至屏幕的大小
        webView.getSettings().setTextZoom(200);


        webView.setWebChromeClient(new WebChromeClient() {
            private AtomicBoolean mIsLoadFinish = new AtomicBoolean(false);

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress == 100) {
                    if (!mIsLoadFinish.compareAndSet(false, true)) {
                        return;
                    }
                  Log.e("wwwww",webView.getContentHeight()+":::"+webView.getWidth());

                    Map<String,String> map = new HashMap<>();
                    map.put("ContentHeight",webView.getContentHeight()+"");
                    viewHeight=webView.getContentHeight();
                    mChannel.invokeMethod("addAndroidWebViewHeightFlutter",map);

                    LoginTimeAccount();

                }
            }

        });

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            webView.getSettings().setMixedContentMode(webView.getSettings().MIXED_CONTENT_ALWAYS_ALLOW);  //注意安卓5.0以上的权限
        }
//        webView.setOnTouchListener(new View.OnTouchListener() {
//            private float startx;
//            private float starty;
//            private float offsetx;
//            private float offsety;
//
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                switch (event.getAction()) {
//                    case MotionEvent.ACTION_DOWN:
//                        v.getParent().requestDisallowInterceptTouchEvent(true);
//                        startx = event.getX();
//                        starty = event.getY();
//                        break;
//                    case MotionEvent.ACTION_MOVE:
//                        offsetx = Math.abs(event.getX() - startx);
//                        offsety = Math.abs(event.getY() - starty);
//                        if (offsetx > offsety) {
//                            v.getParent().requestDisallowInterceptTouchEvent(true);
//                        } else {
//                            v.getParent().requestDisallowInterceptTouchEvent(false);
//                        }
//                        break;
//                    default:
//                        break;
//                }
//                return false;
//            }
//        });
        Log.e("riceView",map.toString());
        Log.e("riceView",map.get("urlData").toString());
        webView.loadDataWithBaseURL(null, (String) map.get("urlData"), "text/html", "UTF-8", null);


    }

    //开始计时
    public void LoginTimeAccount(){

        try {
            if(mTimer == null){
                mTimer = new Timer();
            }
            if(mTimer != null && mTask != null){
                mTask.cancel();
            }
            mTask = new TimerTask() {
                @Override
                public void run() {
                    mContext.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.e("height::",webView.getContentHeight()+"");
                            if (viewHeight!=webView.getContentHeight()){
                                Map<String,String> map = new HashMap<>();
                                map.put("ContentHeight",webView.getContentHeight()+"");
                                viewHeight=webView.getContentHeight();
                                mChannel.invokeMethod("addAndroidWebViewHeightFlutter",map);
                            }
                        }
                    });



                }
            };
            mTimer.schedule(mTask,3000);
//            mTimer.schedule(mTask,1000,1000);
        }catch (Exception e){

        }


    }

    //取消计时
    public void cancelTimeAccount(){
        try {
            if(mTimer != null){
                mTask.cancel();
                mTimer.cancel();
                mTimer = null;
            }
        }catch (Exception e){

        }

    }


    /**
     * 返回嵌入到Flutter页面中的安卓原生view
     * @return
     */
    @Override
    public View getView() {
        return mNativeView;
    }

    /**
     * Flutter传递过来的富文本数据
     */
    public void showFlutterDataForWebView(String data){

    }
    @Override
    public void onFlutterViewAttached(@NonNull View flutterView) { }
    @Override
    public void onFlutterViewDetached() { }
    @Override
    public void dispose() { cancelTimeAccount();}


}

